package com.antdesignbackend.backend.production.reservation.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.antdesignbackend.backend.animalNumber.entity.AnimalNumber;
import com.antdesignbackend.backend.animalNumber.service.AnimalNumberService;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.form.animalApplication.entity.AnimalApplication;
import com.antdesignbackend.backend.service.EnterpriseService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.production.reservation.entity.Reservation;
import com.antdesignbackend.backend.production.reservation.entity.entityVo.ReservationVo;
import com.antdesignbackend.backend.production.reservation.service.ReservationService;

/**
 * 留种记录
 *
 * @author 不二
 * @email reservation
 * @date 2020-08-25 15:09:50
 */

@Controller
@RequestMapping("/reservation")
@Slf4j
public class ReservationController extends BaseController{

	private static final String FUN_NAME = "留种记录";//功能名称
	private Enterprise enterprise;

	@Autowired
	private ReservationService reservationService;
	@Autowired
	EnterpriseService enterpriseService;
	@Autowired
	AnimalNumberService animalNumberService;
	@GetMapping("/index")
	@AuthToken
	public String index() {
		return "production/reservation/index";
	}


	@PostMapping("/tableSearch")
	@ResponseBody
	ReturnVO tableSearch(@RequestBody ReservationVo reservationVo) throws SecurityException, IllegalArgumentException{
		ReturnVO result=new ReturnVO();
		List<ReservationVo> reservations=new ArrayList<>();
		QueryWrapper<ReservationVo> wrapper =new QueryWrapper<>();
		if (reservationVo.getTimeInterval() != null && !reservationVo.getTimeInterval().equals("")){
			String[] str=reservationVo.getTimeInterval().split(" - ");
			String star=str[0];
			String end=str[1];
			wrapper.between("time",star,end);
		}
		wrapper.eq("eid",getLoginEnterpriseId());
		wrapper.orderByDesc("time").orderByDesc("createTime");
		//先统计满足条件的数据总数，因为sql 不包括排序
		int total=reservationService.count(wrapper);
		result.setTotal(total);
		System.out.println("*******************************满足条件的数据有："+total);
		//再查询
		if(total>=0)
		{
			reservations=reservationService.search(wrapper, new Page<ReservationVo>(reservationVo.getPageIndex(),reservationVo.getPageSize()));
		}
		result.setData(reservations);
		return result;
	}

	@GetMapping("/getById/{id}")
	@ResponseBody
	public	Reservation getById(@PathVariable(name = "id") String id) {
		Reservation obj = reservationService.getById(id);
		return obj;
	}

	@PostMapping("/save")
	@ResponseBody
	public ReturnVO save(@RequestBody Reservation reservation){
		ReturnVO result = new ReturnVO();
		reservation.setCreateBy(getLoginUserId());
		reservation.setCreateTime(new Date());
		reservation.setEid(getLoginEnterpriseId());
		AnimalNumber animalNumber=animalNumberService.getById(reservation.getAid());
		UpdateWrapper<AnimalNumber> animalNumberUpdateWrapper=new UpdateWrapper<>();
		if (reservation.getOldType() == 0){ //哺乳
			animalNumberUpdateWrapper.set("lactation",animalNumber.getLactation()-reservation.getNumber());
		}else if (reservation.getOldType() == 1){ //保育
			animalNumberUpdateWrapper.set("conservation",animalNumber.getConservation()-reservation.getNumber());
		}else if (reservation.getOldType() == 2){ //育成
			animalNumberUpdateWrapper.set("commodity",animalNumber.getCommodity()-reservation.getNumber());
		}
		animalNumberUpdateWrapper.set("reserve",animalNumber.getReserve()+reservation.getNumber()).eq("id",reservation.getAid());
		animalNumberService.update(animalNumberUpdateWrapper);
		//判断
		try {
			reservationService.save(reservation);
			result.setMessage("保存成功！");
			result.setCode("200");
		}catch (Exception e){
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	@PostMapping("update")
	@ResponseBody
	public ReturnVO updateById(@RequestBody Reservation reservation){
		ReturnVO result = new ReturnVO();
			Reservation oldReservation=reservationService.getById(reservation.getId());
			QueryWrapper<AnimalNumber> animalNumberQueryWrapper=new QueryWrapper<>();
			animalNumberQueryWrapper.eq("id",reservation.getAid());
			AnimalNumber animalNumber=animalNumberService.getOne(animalNumberQueryWrapper);
			UpdateWrapper<AnimalNumber> animalNumberUpdateWrapper=new UpdateWrapper<>();
			if (oldReservation.getOldType() == 0){ //哺乳
				animalNumberUpdateWrapper.set("lactation",animalNumber.getLactation()+oldReservation.getNumber());
			}else if (oldReservation.getOldType() == 1){ //保育
				animalNumberUpdateWrapper.set("conservation",animalNumber.getConservation()+oldReservation.getNumber());
			}else if (oldReservation.getOldType() == 2){ //育成
				animalNumberUpdateWrapper.set("commodity",animalNumber.getCommodity()+oldReservation.getNumber());
			}
			animalNumberUpdateWrapper.set("reserve",animalNumber.getReserve()-oldReservation.getNumber()).eq("id",oldReservation.getAid());
			animalNumberService.update(animalNumberUpdateWrapper);		//还原

			Boolean b=reservationService.updateById(reservation);

			QueryWrapper<AnimalNumber> animalNumberQueryWrapper1=new QueryWrapper<>();
			animalNumberQueryWrapper1.eq("id",reservation.getAid());
			AnimalNumber animalNumber1=animalNumberService.getOne(animalNumberQueryWrapper);
			UpdateWrapper<AnimalNumber> animalNumberUpdateWrapper1=new UpdateWrapper<>();
			if (reservation.getOldType() == 0){ //哺乳
				animalNumberUpdateWrapper1.set("lactation",animalNumber1.getLactation()-reservation.getNumber());
			}else if (reservation.getOldType() == 1){ //保育
				animalNumberUpdateWrapper1.set("conservation",animalNumber1.getConservation()-reservation.getNumber());
			}else if (reservation.getOldType() == 2){ //育成
				animalNumberUpdateWrapper1.set("commodity",animalNumber1.getCommodity()-reservation.getNumber());
			}
			animalNumberUpdateWrapper1.set("reserve",animalNumber1.getReserve()+reservation.getNumber()).eq("id",reservation.getAid());
			animalNumberService.update(animalNumberUpdateWrapper1);		//修改
			if(b){
				result.setMessage("保存成功！");
				result.setCode("200");
			}else{
				result.setMessage("保存失败！");
				result.setCode("500");
			}
		return result;
	}

	/**
     * 根据id删除
     */
	@DeleteMapping("/deleteById/{id}")
	@ResponseBody
	public ReturnVO deleteById(@PathVariable Serializable id) {
		ReturnVO result = new ReturnVO();
		Reservation reservation=reservationService.getById(id);
		QueryWrapper<AnimalNumber> animalNumberQueryWrapper=new QueryWrapper<>();
		animalNumberQueryWrapper.eq("id",reservation.getAid());
		AnimalNumber animalNumber=animalNumberService.getOne(animalNumberQueryWrapper);
		UpdateWrapper<AnimalNumber> animalNumberUpdateWrapper=new UpdateWrapper<>();
		if (reservation.getOldType() == 0){ //哺乳
			animalNumberUpdateWrapper.set("lactation",animalNumber.getLactation()+reservation.getNumber());
		}else if (reservation.getOldType() == 1){ //保育
			animalNumberUpdateWrapper.set("conservation",animalNumber.getConservation()+reservation.getNumber());
		}else if (reservation.getOldType() == 2){ //育成
			animalNumberUpdateWrapper.set("commodity",animalNumber.getCommodity()+reservation.getNumber());
		}
		animalNumberUpdateWrapper.set("reserve",animalNumber.getReserve()-reservation.getNumber()).eq("id",reservation.getAid());
		animalNumberService.update(animalNumberUpdateWrapper);		//还原
		if (reservationService.removeById(Integer.parseInt(id.toString())) == true) {
			result.setMessage("删除成功");
		} else {
			result.setMessage("删除失败");
			result.setCode("0");
		}
		return result;
	}

}
